package pl.put.miasi.volleyball;


import java.io.File;

import javax.imageio.ImageIO;

import org.jbox2d.collision.PolygonDef;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.World;
import org.jbox2d.dynamics.joints.RevoluteJointDef;

import processing.core.PImage;

public class B2Net {
	//upper part of net column
	protected Body netEndingPart;

	private World world;
	private Main main;
	private Volleyball volleyball;
	
	public B2Net(Volleyball volleyball) {
		this.volleyball = volleyball;
		this.world =  this.volleyball.m_world;
		this.main = this.volleyball.parent;
		this.netEndingPart = volleyball.netEndingPart;
	}
	
	public void initialize() {
		/*
		 * Create net
		 */		
		PImage netImage = null;
		try {
			netImage = new PImage(ImageIO.read(new File("images/net.gif")));
			netImage.format = 2;
		} catch (Exception e) {
			e.printStackTrace();
		}
		
			PolygonDef meshFixDef = new PolygonDef();
			meshFixDef.setAsBox(0.075f, 0.075f);
			meshFixDef.density = 20.0f;
			meshFixDef.friction = 0.2f;


			RevoluteJointDef jointDef = new RevoluteJointDef();
			jointDef.collideConnected = false;

			float startX = Settings.ACT_WORLD_CENTER_X;
			float startY = Settings.ACT_WORLD_CENTER_Y;

			float endX = Settings.ACT_WORLD_CENTER_X;
			float endY = (Settings.ACT_WORLD_MAX_Y + Settings.ACT_WORLD_MIN_Y) / 4.0f;
			Body prevBody = netEndingPart;
			Body meshBody = null;
			
			float y = startY;
			float x = startX;
			float dy = (startY - endY) / 15.0f;
			
			while (y >= endY) {
				BodyDef meshBodyDef = new BodyDef();
				meshBodyDef.userData = "mesh";
				meshBodyDef.position.set(x, y);
				meshBody = world.createDynamicBody(meshBodyDef);
				meshBody.createShape(meshFixDef);
				meshBody.setMassFromShapes();

				Vec2 anchor = new Vec2(x, y);
				jointDef.initialize(prevBody, meshBody, anchor);
				jointDef.collideConnected = true;
				
				world.createJoint(jointDef);
				
				volleyball.bindImage(netImage, new Vec2(0.0f, 0.0f), 0.0f, 1.0f / Settings.CS, meshBody);

				y -= dy;
				prevBody = meshBody;				
			}

			Vec2 anchor = new Vec2(endX, endY);
			jointDef.initialize(prevBody, netEndingPart, anchor);
			world.createJoint(jointDef);
	}
}
